package com.zhang.threads;

import com.zhang.service.MyService;
import com.zhang.util.RequestHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.util.concurrent.Callable;
import javax.servlet.http.HttpServletRequest;

// 线程类

public class MyTask implements Callable<Void> {
    private HttpServletRequest request;

    private MyService myService;
    private String id;

    public MyTask(HttpServletRequest request,MyService myService,String id) {
        this.request = request;
        this.id =id;
        this.myService = myService;
    }

    @Override
    public Void call() throws Exception {
        // 设置 request 到 RequestHolder
        System.out.println("设置 request 到 RequestHolder");
        RequestHolder.setRequest(request);
        try {
            // 执行具体任务
            doSomething(id);
        } finally {
            // 清理 request
//            RequestHolder.clearRequest();
        }
        return null;
    }

    // 具体任务方法
    public void doSomething(String id) {
        if (!ObjectUtils.isEmpty(request)){
            System.out.println("线程前的: "+request.getRequestURI());
        }

        String s = myService.execMethod(id);
        if (!ObjectUtils.isEmpty(request)){
            String getRequestURI = request.getRequestURI();
            System.out.println("线程后的: "+getRequestURI);
        }
    }
}    